package middleware

import (
	"encoding/json"
	"fmt"
)

func JSONMessageWrap(handler func(context Context) interface{}) Handler {
	return func(context Context, next Next) error {
		// 错误由上游处理，无需管理
		_ = next(nil)
		if context.IsClose() {
			fmt.Println("close")
			return nil
		}
		response := handler(context)
		return JSONMessage(response, context)
	}
}

func JSONMessage(response interface{}, context Context) error {
	writer := context.Writer()
	writer.Header().Set("Content-Type", "application/json")
	return json.NewEncoder(writer).Encode(response)
}
